#include "tictactoe.h"
#include "button.h"
#include <QGridLayout>
#include <QMessageBox>

TicTacToe::TicTacToe(QWidget *parent) :
        QDialog(parent), last_state(ZERO), winner(EMPTY)
{
    QGridLayout *grid = new QGridLayout();
    setLayout(grid);
    for (size_t i = 0; i < 3; ++i)
        for (size_t j = 0; j < 3; ++j)
        {
            grid->addWidget(new Button(this, i, j), i, j);
            states[i*3 + j] = EMPTY;
        }
}

States TicTacToe::getState(int row, int col)
{
    if (winner != EMPTY)
    {
//        QMessageBox msg;
//        msg.setText("Game is over!");
//        msg.exec();
        return EMPTY;
    }

    if (last_state == ZERO)
        last_state = CROSS;
    else
        last_state = ZERO;
    states[row * 3 + col] = last_state;
    return last_state;
}

States TicTacToe::getWinner()
{
    States s = EMPTY;

    if (   check(0, 1, 2, s)
        || check(3, 4, 5, s)
        || check(6, 7, 8, s)
        || check(0, 3, 6, s)
        || check(1, 4, 7, s)
        || check(2, 5, 8, s)
        || check(0, 4, 8, s)
        || check(2, 4, 6, s))
    {
        winner = s;
    }

    return s;
}

bool TicTacToe::check(int i, int j, int k, States& s)
{
    if ((states[i] == states[j]) && (states[j] == states[k]))
    {
        s = states[i];
        return true;
    }
    return false;
}
